package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 *
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final String url="https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User UserLogin(UserLoginDTO userLoginDTO) throws Exception {

        //调用微信官方接口，获取用户的openid
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("appid",weChatProperties.getAppid());
        requestMap.put("secret",weChatProperties.getSecret());
        requestMap.put("js_code",userLoginDTO.getCode());
        requestMap.put("grant_type","authorization_code");
        String resultEntry = HttpClientUtil.doGet(url, requestMap);
        JSONObject jsonObject = new JSONObject(resultEntry);
        String openid = (String)jsonObject.get("openid");
        //判断是否成功获取openid
        if (StringUtils.isBlank(openid)){
            throw  new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断该用户是否为新用户，新用户要做新增
        User user = userMapper.getUserByOpenid(openid);
        if (user== null){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }

        log.info("用户登录成功，用户id：{}",user.getId());

        return user;
    }
}
